﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RunZ;
public class UIManager : RZSingleton<UIManager>
{
    private Dictionary<int, RZUIBaseCtrl> UIDics;

    public UIManager()
    {
        UIDics = new Dictionary<int, RZUIBaseCtrl> ();

        // eventManager 管理
        var emger = EventManager.SP;
        emger.AddEvent (UIEvent.UICreate, _onCreateUI, this);
        emger.AddEvent (UIEvent.UIShow, _onShowUI, this);
        emger.AddEvent (UIEvent.UIHide, _onHideUI, this);
        emger.AddEvent (UIEvent.UIUserData, _onUserData, this);
        emger.AddEvent (UIEvent.UIDestroy, _onDestroyUI, this);
        emger.AddEvent (UIEvent.UIDestroyAll, _onDestroyUIAll, this);
    }

    /// <summary>
    /// UI 寄存器
    /// </summary>
    public void RegisterUICtrl(int uiID, RZUIBaseCtrl ctrl)
    {
        UIDics.Add (uiID, ctrl);
    }

    /// <summary>
    /// 从寄存器中删除
    /// </summary>
    public void RemoveUICtrl(int uiID)
    {
        RZUIBaseCtrl result;
        if(UIDics.TryGetValue(uiID, out result))
        {
            result.DestroyUI ();
            UIDics.Remove (uiID);
        }
    }

    /// <summary>
    /// 获取ID对应UI界面
    /// </summary>
    public RZUIBaseCtrl GetUICtrl (int uiID)
    {
        RZUIBaseCtrl result;
        if(UIDics.TryGetValue (uiID, out result))
        {
            return result;
        }
        return null;
    }
    
    private void _onCreateUI(string tag, params object[] args)
    {
        int uiid = (int)args[0];

        RZUIBaseCtrl uiCtrl = GetUICtrl (uiid);
        if (uiCtrl == null) return;

        uiCtrl.CreateUI ();
    }

    private void _onShowUI(string tag, params object[] args)
    {
        int uiid = (int)args[0];

        RZUIBaseCtrl uiCtrl = GetUICtrl (uiid);
        if (uiCtrl == null) return;

        if (!uiCtrl.Show ()) uiCtrl.CreateUI ();
    }

    private void _onHideUI(string tag, params object[] args)
    {
        int uiid = (int)args[0];

        RZUIBaseCtrl uiCtrl = GetUICtrl (uiid);
        if (uiCtrl == null) return;
        
        if(uiCtrl.IsShow) { uiCtrl.Hide (); }
    }

    private void _onDestroyUI(string tag, object[] args)
    {
        int uiid = (int)args[0];

        RZUIBaseCtrl uiCtrl = GetUICtrl (uiid);
        if (uiCtrl == null) return;
        uiCtrl.DestroyUI ();
    }


    private void _onDestroyUIAll(string tag, object[] args)
    {
        foreach (var itag in UIDics)
        {
            itag.Value.DestroyUI ();
        }
    }

    private void _onUserData(string tag, params object[] args)
    {
        int uiid = (int)args[0];

        RZUIBaseCtrl uiCtrl = GetUICtrl (uiid);
        if (uiCtrl == null) return;
        uiCtrl.UserData = args[1];
    }
}
